package com.example.jetpacktest.activity

import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.work.*
import com.example.jetpacktest.work.MyWork001
import com.example.jetpacktest.work.MyWork002
import com.example.jetpacktest.work.MyWork003
import com.example.jetpacktest.work.MyWork004
import com.google.common.util.concurrent.ListenableFuture
import java.util.concurrent.TimeUnit

class Test004Activity : AppCompatActivity() {

    private val TAG: String = this.javaClass.simpleName

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        test012()
    }

    override fun onDestroy() {
        super.onDestroy()
        //WorkManager.getInstance(this).cancelAllWork()
    }

    /**
     * 一次性
     */
    private fun test001(){
        val workRequest: WorkRequest = OneTimeWorkRequestBuilder<MyWork001>().build()
        WorkManager.getInstance(this).enqueue(workRequest)
    }

    /**
     * 周期性
     */
    private fun test002(){
        //时间间隔不能小于15分钟，小于15分钟无效
        //The repeat interval must be greater than or equal to PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS and
        // the flex interval must be greater than or equal to PeriodicWorkRequest.MIN_PERIODIC_FLEX_MILLIS.
        val workRequest: WorkRequest = PeriodicWorkRequestBuilder<MyWork001>(16, TimeUnit.MINUTES).build()
        WorkManager.getInstance(this).enqueue(workRequest)
    }

    /**
     * 添加约束
     */
    private fun test003(){
        val constraints: Constraints = Constraints.Builder()
            .setRequiredNetworkType(NetworkType.UNMETERED) //不限流量网络
            .build()
        val workRequest: WorkRequest = OneTimeWorkRequestBuilder<MyWork001>()
            .setConstraints(constraints)
            .build()
        WorkManager.getInstance(this).enqueue(workRequest)

    }

    /**
     * 添加和获取tag
     */
    private fun test004(){
        val workRequest: WorkRequest = OneTimeWorkRequestBuilder<MyWork001>()
            .addTag("hehe")
            .setInitialDelay(3, TimeUnit.MINUTES)
            .build()
        WorkManager.getInstance(this).enqueue(workRequest)
        workRequest.tags.forEach {
            Log.d(TAG, "tag = $it")
        }
        Log.d(TAG, "tags的size = ${workRequest.tags.size}")
    }


    /**
     * 传递数据到Worker中
     */
    private fun test005(){
        val data:Data = workDataOf("KeyMyUploadUrl" to "www.whctco.com")
        //val data: Data = Data.Builder().put("KeyMyUploadUrl", "www.baidu.com").build()
        val workRequest: WorkRequest = OneTimeWorkRequestBuilder<MyWork002>()
            .setInputData(data)
            .build()
        WorkManager.getInstance(this).enqueue(workRequest)
    }


    /**
     * Unique Work
     */
    private fun test006(){
        val workRequest = OneTimeWorkRequestBuilder<MyWork001>().build()
        val workManager = WorkManager.getInstance(this)
        workManager.enqueueUniqueWork(
            "myWork001UniqueName",
            ExistingWorkPolicy.KEEP, workRequest
        )
        workManager.enqueueUniqueWork(
            "myWork001UniqueName",
            ExistingWorkPolicy.KEEP, workRequest
        )
        workManager.enqueueUniqueWork(
            "myWork001UniqueName",
            ExistingWorkPolicy.KEEP, workRequest
        )
        val workInfo = workManager.getWorkInfosForUniqueWork("myWork001UniqueName")
        workInfo.get().forEach {
            Log.d(TAG, "workInfo = $it")
        }

    }


    /**
     * Observing your work
     */
    private fun test007() {
        val workRequest = OneTimeWorkRequestBuilder<MyWork001>().build()
        Log.d(TAG, "word的id = ${workRequest.id}")
        val workManager = WorkManager.getInstance(this)
        workManager.enqueueUniqueWork(
            "test007Work",
            ExistingWorkPolicy.KEEP, workRequest
        )
        workManager.getWorkInfoByIdLiveData(workRequest.id).observe(this,
            Observer<WorkInfo> { workInfo: WorkInfo? ->
                if (workInfo?.state == WorkInfo.State.SUCCEEDED) {
                    Log.d(TAG, "任务成功")
                    //Toast.makeText(this, "任务成功", Toast.LENGTH_SHORT).show()
                } else {
                    Log.d(TAG, "任务失败")
                    //Toast.makeText(this, "任务失败", Toast.LENGTH_SHORT).show()
                }
            })

    }


    /**
     * 通过WorkQuery查询
     */
    private fun test008(){
        val workRequest1 = OneTimeWorkRequestBuilder<MyWork001>()
            .addTag("tagWork1")
            .setInitialDelay(1, TimeUnit.MINUTES)
            .build()
        val workRequest2: OneTimeWorkRequest = OneTimeWorkRequestBuilder<MyWork002>()
            .setInputData(workDataOf("KeyMyUploadUrl" to "www.mm.cn"))
            .addTag("tagWork2")
            .setInitialDelay(2, TimeUnit.MINUTES)
            .build()
        val workManager: WorkManager = WorkManager.getInstance(this)
        workManager.enqueue(workRequest1)
        workManager.enqueueUniqueWork("workRequest2UniqueName", ExistingWorkPolicy.KEEP, workRequest2)

        //开始查询
        //val workQuery: WorkQuery = WorkQuery.Builder.fromTags(listOf("tagWork1")).build()
        val workQuery: WorkQuery = WorkQuery.Builder
            .fromTags(listOf("tagWork2"))
            .addUniqueWorkNames(listOf("workRequest2UniqueName"))
            .build()
        val workInfos: List<WorkInfo> = workManager.getWorkInfos(workQuery).get()
        Log.d(TAG, "workInfos的大小 = ${workInfos.size}")
        workInfos.forEach {
            Log.d(TAG, "查询出来的workInfo = $it")
        }
    }


    /**
     * Stop a running Worker
     */
    private fun test009(){
        val workRequest: WorkRequest = OneTimeWorkRequestBuilder<MyWork001>()
            .setInitialDelay(1, TimeUnit.MINUTES)
            .build()
        val workManager: WorkManager = WorkManager.getInstance(this)
        workManager.enqueue(workRequest)
        Thread.sleep(100)
        workManager.cancelWorkById(workRequest.id)
    }


    /**
     * 查看工作进度
     */
    private fun test010(){
        val workRequest: WorkRequest = OneTimeWorkRequestBuilder<MyWork003>().build()
        val workManager: WorkManager = WorkManager.getInstance(this)
        workManager.enqueue(workRequest)
        workManager.getWorkInfoByIdLiveData(workRequest.id).observe(this, Observer<WorkInfo> { workInfo: WorkInfo? ->
            if (workInfo?.state == WorkInfo.State.RUNNING) { //运行中才打印进度
                Log.d(TAG, "工作进度 = ${workInfo.progress}")
            }

        })
    }


    /**
     * Chaining Work
     */
    private fun test011(){
        val workRequest1: OneTimeWorkRequest = OneTimeWorkRequestBuilder<MyWork001>().build()
        val workRequest2: OneTimeWorkRequest = OneTimeWorkRequestBuilder<MyWork002>()
            .setInputData(workDataOf("KeyMyUploadUrl" to "www.xx.com"))
            .build()
        val workRequest3: OneTimeWorkRequest = OneTimeWorkRequestBuilder<MyWork003>().build()
        val workManager: WorkManager = WorkManager.getInstance(this)
        //组成链状
        /*workManager
            .beginWith(workRequest1)
            .then(workRequest2)
            .then(workRequest3)
            .enqueue()*/

        //1和2并行，3需要等1和2都执行完了之后才开始
        workManager
            .beginWith(listOf(workRequest1, workRequest2))
            .then(workRequest3)
            .enqueue()
    }


    /**
     * Creating and managing long-running workers
     */
    private fun test012(){
        val workRequest: WorkRequest = OneTimeWorkRequestBuilder<MyWork004>()
            .setInputData(workDataOf(MyWork004.KEY_URL to "www.xxx.cn",
                MyWork004.KEY_OUTPUT_FILE_NAME to "001.exe"))
            .build()
        val workManager: WorkManager = WorkManager.getInstance(this)
        workManager.enqueue(workRequest)
    }





}